<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2018/3/9
 * Time: 11:36
 */

namespace App\Api\Service\Buyers\Controllers;

use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\Buyers;
use App\Engine\Func;
use App\Eloquent\Ygt\DepartmentUser;

use App\Eloquent\Ygt\CustomerBuyer;

class IndexController extends Controller
{
    public function getList(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $buyersModel = new Buyers();
        $where = [
            'company_id'=>$companyId
        ];
        if($buyerName = request('buyer_name')){
            $where['buyer_name'] = ['like','%'.$buyerName.'%'];
        }
        if($customerId = request('customer_id')){
            $buyerIds = CustomerBuyer::where(['customer_id'=>$customerId])->get()->pluck('buyer_id');
            $where['id'] = ['in',$buyerIds];
        }

        $fields = '*';

        $page = request('page');
        $limit = 10;
        $offset = ($page - 1) * $limit;

        $result = $buyersModel->getData($where, $fields, $limit, $offset);

        $list = $result->map(function($item, $key){
            return $this->composeInfo($item);
        })->toArray();

        $count = $buyersModel->getCount($where);

        $pagingData = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($list, $pagingData);
    }

    private function composeInfo($item){
        $tmp = [
            'id'=>$item->id,
            'buyer_name'=>$item->buyer_name,
            'customer_id'=>$item->customer_id,
            'customer_name'=>isset($item->customer->customer_name)?$item->customer->customer_name:'',
        ];
        return $tmp;
    }

    public function getAll(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $buyersModel = new Buyers();
        $where = [
            'company_id'=>$companyId
        ];
        if($buyerName = request('buyer_name')){
            $where['buyer_name'] = ['like','%'.$buyerName.'%'];
        }
        if($customerId = request('customer_id')){
            $buyerIds = CustomerBuyer::where(['customer_id'=>$customerId])->get()->pluck('buyer_id');
            $where['id'] = ['in',$buyerIds];
        }

        $fields = '*';

        $result = $buyersModel->getData($where, $fields);

        $list = $result->map(function($item, $key){
            return $this->composeInfo($item);
        })->toArray();
        return $list;

    }

    public function getInfo(){
        $where = [
            'id'=>request('id')
        ];
        $rules = [
            'id' => 'required|integer',
        ];
        $this->validateRequestParameters($where, $rules);

        $userId = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';
        $where['company_id'] = $companyId;

        $buyersModel = new Buyers();
        if($item = $buyersModel->getOneData($where)){
            $info = $this->composeInfo($item);
            return $info;
        }else{
            xThrow(ERR_CUSTOMER_IS_NOT_EXIST);
        }
    }


    public function buyersAdd(){
        $params = request()->only('buyer_name', 'customer_id');

        $params['customer_id'] = $params['customer_id']?$params['customer_id']:0;

        $user_id        = Func::getHeaderValueByName( 'userid' );
        $userinfo           = DepartmentUser::getCurrentInfo( $user_id );

        $rules = [
            'buyer_name' => 'required',
            'customer_id' => 'integer',
        ];
        $this->validateRequestParameters($params, $rules);


        //同一个客户下 单位名称不能重复
        $buyersRow = \App\Eloquent\Ygt\Buyers::where(['customer_id'=>$params['customer_id'],'buyer_name'=>$params['buyer_name']])->first();
        if($buyersRow){
            return [
                'code' => 1,
                'message' => '单位名称已存在'
            ];
        }



        $buyersModel = new Buyers();

        $createData = [
            'buyer_name' => $params['buyer_name'],
            'customer_id' => $params['customer_id'],
            'company_id' => $userinfo->company_id,
        ];
        $buyersId = $buyersModel->insertOneData($createData,'id');

        $returnData = [
            'msg'=>'ok',
            'id'=>$buyersId
        ];
        return $returnData;

    }

    public function buyersEdit(){

        $params = request()->only('id', 'buyer_name', 'customer_id');

        $params['customer_id'] = $params['customer_id']?$params['customer_id']:0;

        $user_id        = Func::getHeaderValueByName( 'userid' );
        $userinfo           = DepartmentUser::getCurrentInfo( $user_id );

        $rules = [
            'id' => 'required|integer',
            'buyer_name' => 'required',
            'customer_id' => 'integer',
        ];
        $this->validateRequestParameters($params, $rules);

        $buyersModel = new Buyers();

        $createData = [
            'buyer_name' => $params['buyer_name'],
            'customer_id' => $params['customer_id'],
            'company_id' => $userinfo->company_id,
        ];
        $where = ['id'=>$params['id']];

        //同一个客户下 单位名称不能重复；修改时，只能改为不重名或者原名
        $curBuyersRow = \App\Eloquent\Ygt\Buyers::where(['id'=>$params['id']])->first();
        if($curBuyersRow){
            if($curBuyersRow['buyer_name'] != $params['buyer_name']){
                $buyersRow = \App\Eloquent\Ygt\Buyers::where(['customer_id'=>$params['customer_id'],'buyer_name'=>$params['buyer_name']])->first();
                if($buyersRow){
                    return [
                        'code' => 1,
                        'message' => '单位名称已存在'
                    ];
                }
            }
        }





        if(!$buyersId = $buyersModel->updateOneData($where, $createData,'id')){
            xThrow(ERR_CUSTOMER_IS_NOT_EXIST);
        }

        $returnData = [
            'msg'=>'ok',
            'buyers_id'=>$buyersId
        ];
        return $returnData;

    }

    public function buyersDel()
    {
        $userId = Func::getHeaderValueByName('userid');
        $userInfo = DepartmentUser::getCurrentInfo($userId);
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $buyerId = request('id');
        $where = [
            'id'=>$buyerId,
            'company_id'=>$companyId,
        ];
        $buyersModel = new Buyers();
        if($buyersModel->del($where)){
            return 'ok';
        }else{
            xThrow(ERR_CUSTOMER_DELETE_FAIL);
        }

    }

    //单位-品命-列表
    public function getBuyersProductList(){
        $buyerId = request('buyers_id');

        $fileList = [
            'id',
            'buyers_id',
            'name',
            'is_default',
        ];

        $buyersProductList = \App\Eloquent\Ygt\BuyersProduct::where(['buyers_id' => $buyerId])->orderBy('is_default','desc')->get($fileList)->toArray();

        //返回和版相关的图片
        foreach($buyersProductList as $key => $buyersProductRow){
            $tmpImgIdList = [];
            $tmpImgUrlList = [];
            $tmpPlateList = \App\Eloquent\Ygt\Plate::where(['plate_name'=>$buyersProductRow['id']])->get()->toArray();

            foreach ($tmpPlateList as $tmpPlateRow){
                $tmpImgId = $tmpPlateRow['img_id'];
                //获取图片路径
                if ($tmpImgId) {
                    $imageUrl = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($tmpImgId, true, false);
                    $tmpImgIdList[] = $tmpImgId;
                    $tmpImgUrlList[] = $imageUrl;
                }

                //片料规格
                if($tmpPlateRow['chip_specification_length']){
                    $buyersProductList[$key]['chip_specification_length'] = $tmpPlateRow['chip_specification_length'];
                }

                //成品规格
                if($tmpPlateRow['finished_specification']){
                    $buyersProductList[$key]['finished_specification'] = $tmpPlateRow['finished_specification'];
                }
            }

            $buyersProductList[$key]['img_id_list'] = $tmpImgIdList;
            $buyersProductList[$key]['img_url_list'] = $tmpImgUrlList;
        }


        return $buyersProductList;
    }

    //单位-品命-添加&修改
    public function editBuyersProduct(){
        $buyerProductId = request('buyers_product_id');

        $buyersId = request('buyers_id');
        $name = request('name');
        $isDefualt = request('is_default');

        //如果设为默认值，将原来的默认值置为非默认值
        if($isDefualt){
            \App\Eloquent\Ygt\BuyersProduct::where(['buyers_id' => $buyersId])->update(['is_default'=>0]);
        }

        ////同一个客户下 品名不能重复
        //获取客户ID
        $customerId = '';
        $tmpBuyersRow =  \App\Eloquent\Ygt\Buyers::where(['id'=>$buyersId])->first();
        if($tmpBuyersRow){
            $customerId = $tmpBuyersRow->customer_id;
        }
        if($customerId){
            $buyersIdArr = \App\Eloquent\Ygt\Buyers::where(['customer_id'=>$customerId])->get()->pluck('id');

            //修改时，品名只能为不同品名，或者和原品名相同
            if($buyerProductId){
                $curBuyersProductRow = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$buyerProductId])->first();
                if($curBuyersProductRow){
                    if($curBuyersProductRow['name'] != $name){
                        $tmpBuyersProductRow =  \App\Eloquent\Ygt\BuyersProduct::whereIn('buyers_id',$buyersIdArr)->where(['name'=>$name])->first();
                        if($tmpBuyersProductRow){
                            if(!$buyerProductId || $tmpBuyersProductRow['id'] != $buyerProductId){
                                return [
                                    'code' => 1,
                                    'message' => '品名已存在'
                                ];
                            }
                        }
                    }
                }

            }else{
                $tmpBuyersProductRow =  \App\Eloquent\Ygt\BuyersProduct::whereIn('buyers_id',$buyersIdArr)->where(['name'=>$name])->first();
                if($tmpBuyersProductRow){
                    if(!$buyerProductId || $tmpBuyersProductRow['id'] != $buyerProductId){
                        return [
                            'code' => 1,
                            'message' => '品名已存在'
                        ];
                    }
                }
            }

        }




        $buyersProductObj = \App\Eloquent\Ygt\BuyersProduct::firstOrNew(['id' =>$buyerProductId]);
        $editRow = [
            'buyers_id' => $buyersId,
            'name' => $name,
            'is_default' => $isDefualt,
        ];
        $buyersProductObj->fill($editRow);
        $buyersProductObj->save();

        return '操作成功';

    }

    //单位-品命-删除
    public function delBuyersProduct(){
        $buyerProductId = request('buyers_product_id');
        \App\Eloquent\Ygt\BuyersProduct::where(['id' => $buyerProductId])->first()->delete();

        return '操作成功';
    }





    //单位-开票资料-列表
    public function getBuyersInvoiceList(){
        $userId = Func::getHeaderValueByName('userid');
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        $buyerId = request('buyers_id');


        $result = \App\Eloquent\Ygt\BuyersInvoice::where(['buyers_id' => $buyerId])->orderBy('is_default','desc')->get();

        $list = $result->map(function($item, $key){
            $item->buyersInfo = \App\Eloquent\Ygt\Buyers::where(['id'=>$item->buyers_id])->first();
            return $this->buyersInvoiceListComposeInfo($item);
        })->toArray();

        return $list;
    }

    private function buyersInvoiceListComposeInfo($item){
        $tmp = [
            'id'=>$item->id,
            'account_name'=>$item->account_name,
            'telphone'=>$item->telphone,
            'taxpayer_number'=>$item->taxpayer_number,
            'opening_bank'=>$item->opening_bank,
            'bank_card_number'=>$item->bank_card_number,
            'buyers_id'=>$item->buyers_id,
            'buyers_name'=>isset($item->buyersInfo->buyer_name)?$item->buyersInfo->buyer_name:'',
            'province_id'=>$item->province_id,
            'city_id'=>$item->city_id,
            'area_id'=>$item->area_id,
            'province_name'=>$item->province_name,
            'city_name'=>$item->city_name,
            'area_name'=>$item->area_name,
            'address'=>$item->address,
            'is_default'=>$item->is_default,
        ];
        return $tmp;
    }

    //单位-开票资料-添加&修改
    public function editBuyersInvoice(){
        $params = request()->only('buyers_invoice_id','account_name', 'telphone', 'taxpayer_number', 'opening_bank', 'bank_card_number', 'buyers_id', 'province_id', 'city_id', 'area_id', 'address', 'is_default');

        $params['buyers_id'] = $params['buyers_id']?$params['buyers_id']:0;
        $params['buyers_invoice_id'] = $params['buyers_invoice_id']?$params['buyers_invoice_id']:0;

        $user_id        = Func::getHeaderValueByName( 'userid' );
        $userInfo           = DepartmentUser::getCurrentInfo( $user_id );
        $companyId = isset($userInfo['company_id']) ? $userInfo['company_id'] : '';

        if($params['province_id'] == '(null)'){//过滤异常传入值
            $params['province_id'] = '';
        }

        $rules = [
            'account_name' => 'required',
            'telphone' => 'required',
            'taxpayer_number' => 'required',
            'opening_bank' => 'required',
            'bank_card_number' => 'required',
            'buyers_id' => 'required|integer',
            'is_default' => 'required|integer',
            'province_id' => 'required',
        ];
        $this->validateRequestParameters($params, $rules);

        if($params['is_default'] == 1){
            \App\Eloquent\Ygt\BuyersInvoice::where(['buyers_id' => $params['buyers_id']])->update(['is_default'=>0]);
        }

        $provinceInfo = \App\Eloquent\Province::where('provinceID',$params['province_id'])->first();
        $cityInfo = \App\Eloquent\City::where('cityID',$params['city_id'])->first();
        $areaInfo = \App\Eloquent\Area::where('areaID',$params['area_id'])->first();
        $editData = [
            'account_name' => $params['account_name'],
            'telphone' => $params['telphone'],
            'taxpayer_number' => $params['taxpayer_number'],
            'opening_bank' => $params['opening_bank'],
            'bank_card_number' => $params['bank_card_number'],
            'buyers_id' => $params['buyers_id'],
            'province_id' => $params['province_id'],
            'city_id' => $params['city_id'],
            'area_id' => $params['area_id'],
            'province_name' => isset($provinceInfo->province)?$provinceInfo->province:'',
            'city_name' => isset($cityInfo->city)?$cityInfo->city:'',
            'area_name' => isset($areaInfo->area)?$areaInfo->area:'',
            'address' => $params['address'],
            'is_default' => $params['is_default'],
            'company_id' => $companyId,
        ];


        $buyersInvoiceObj = \App\Eloquent\Ygt\BuyersInvoice::firstOrNew(['id'=>$params['buyers_invoice_id']]);
        $buyersInvoiceObj->fill($editData);
        $buyersInvoiceObj->save();

        return '操作成功';

    }

    //单位-开票资料-删除
    public function delBuyersInvoice(){

        $buyerInvoiceId = request('buyers_invoice_id');
        \App\Eloquent\Ygt\BuyersInvoice::where(['id' => $buyerInvoiceId])->first()->delete();

        return '操作成功';

    }

    //单位详情信息（包含子栏目数量）
    public function getBuyersList()
    {
//        $customerId = request('customer_id');
//
//        $buyersList = \App\Eloquent\Ygt\Buyers::where(['customer_id'=>$customerId])->orderBy('id','desc')->get(['id','buyer_name'])->toArray();
//
//        foreach ($buyersList as $key => $buyersRow){
//            $tmpBuyersId = $buyersRow['id'];
//            $tmpBuyersInvoiceCount = \App\Eloquent\Ygt\BuyersInvoice::where(['buyers_id'=>$tmpBuyersId])->get()->count();
//            $tmpBuyersProductCount = \App\Eloquent\Ygt\BuyersProduct::where(['buyers_id'=>$tmpBuyersId])->get()->count();
//            $tmpBuyersAddressCount = \App\Eloquent\Ygt\BuyersAddress::where(['buyers_id'=>$tmpBuyersId])->get()->count();
//            $buyersList[$key]['buyers_invoice_cout'] = $tmpBuyersInvoiceCount;
//            $buyersList[$key]['buyers_product_cout'] = $tmpBuyersProductCount;
//            $buyersList[$key]['buyers_address_cout'] = $tmpBuyersAddressCount;
//        }

        $customerId             = request('customer_id',0);
        if(!$customerId)
        {
            xThrow(ERR_PARAMETER);
        }
        //单位列表
        $where                  = ['customer_id'=>$customerId];
        $columns                = ['id','buyer_name'];
        $query                  = \App\Eloquent\Ygt\Buyers::where($where)->select($columns);
        $query                  = $query->orderBy('id','desc');
        $buyersList             = $query->get()->toArray();
        //单位列表对应的品名,地址,开票列表
        $buyersIdArr            = [];
        $obj                    = new \stdClass();
        foreach($buyersList as $key=>$val)
        {
            $buyersIdArr[]      = $val['id'];
            //默认值
            $buyersList[$key]['buyers_invoice_cout'] = 0;
            $buyersList[$key]['buyers_product_cout'] = 0;
            $buyersList[$key]['buyers_address_cout'] = 0;
            //有值则返,无值则字段都不要!!!!!!!!!!安卓
//            $buyersList[$key]['buyers_invoice_obj'] = $obj;
//            $buyersList[$key]['buyers_product_obj'] = $obj;
//            $buyersList[$key]['buyers_address_obj'] = $obj;
        }
        if(!empty($buyersIdArr))
        {
            //品名
            $columns        = [
                'id','buyers_id','name','is_default'
            ];
            $query          = \App\Eloquent\Ygt\BuyersProduct::whereIn('buyers_id',$buyersIdArr);
            $query          = $query->select($columns);
            $productList    = $query->get()->toArray();
            //地址
            $columns        = [
                'id','buyers_id','consignee','phone','province_id','city_id','area_id',
                'address','province_name','city_name','area_name','is_default'
            ];
            $query          = \App\Eloquent\Ygt\BuyersAddress::whereIn('buyers_id',$buyersIdArr);
            $query          = $query->select($columns);
            $addressList    = $query->get()->toArray();
            //开票
            $columns        = ['*'];
            $query          = \App\Eloquent\Ygt\BuyersInvoice::whereIn('buyers_id',$buyersIdArr);
            $query          = $query->select($columns);
            $invoiceList    = $query->get()->toArray();
            foreach($buyersList as $key=>$val)
            {
                $buyersId       = $val['id'];
                //品名
                $productArr     = $this->getBuyersRelation($buyersId,$productList);
                $productSize    = $productArr['size'];
                $productObj     = $productArr['obj'];
                //地址
                $addressArr     = $this->getBuyersRelation($buyersId,$addressList);
                $addressSize    = $addressArr['size'];
                $addressObj     = $addressArr['obj'];
                //开票
                $invoiceArr     = $this->getBuyersRelation($buyersId,$invoiceList);
                $invoiceSize    = $invoiceArr['size'];
                $invoiceObj     = $invoiceArr['obj'];

                $buyersList[$key]['buyers_invoice_cout'] = $invoiceSize;
                $buyersList[$key]['buyers_product_cout'] = $productSize;
                $buyersList[$key]['buyers_address_cout'] = $addressSize;
                if(!empty($invoiceObj))
                {
                    $buyersList[$key]['buyers_invoice_obj'] = $invoiceObj;
                }
                if(!empty($productObj))
                {
                    //添加品名对应的版设置的片料规格和成品规格 zhuyujun 20181213
                    $tmpPlateRow = \App\Eloquent\Ygt\Plate::where(['plate_name'=>$productObj['id']])->first();
                    $productObj['chip_specification_length'] = $tmpPlateRow['chip_specification_length'] ? $tmpPlateRow['chip_specification_length'] : '';
                    $productObj['finished_specification'] = $tmpPlateRow['finished_specification'] ? $tmpPlateRow['finished_specification'] : '';

                    $buyersList[$key]['buyers_product_obj'] = $productObj;
                }
                if(!empty($addressObj))
                {
                    $buyersList[$key]['buyers_address_obj'] = $addressObj;
                }
//                $buyersList[$key]['buyers_invoice_obj'] = $invoiceObj;
//                $buyersList[$key]['buyers_product_obj'] = $productObj;
//                $buyersList[$key]['buyers_address_obj'] = $addressObj;
            }
        }
        return $buyersList;
    }
    private function getBuyersRelation($buyersId,$lists)
    {
        $size           = 0;
        //$obj            = new \stdClass();
        $obj            = [];
        foreach($lists as $key=>$val)
        {
            $valBuyersId    = $val['buyers_id'];
            if($buyersId == $valBuyersId)
            {
                $size       += 1;
                if($val['is_default'] == 1)
                {
                    $obj    = $val;
                }
            }
        }
        $result         = [
            'size'=>$size,
            'obj'=>$obj,
        ];
        return $result;
    }










}